package top.pengdong.dachuang.main.service.impl;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import top.pengdong.common.utils.ResultCode;
import top.pengdong.common.utils.ResultResponse;
import top.pengdong.dachuang.main.dao.UserMapper;
import top.pengdong.dachuang.main.mbg.model.UserExample;
import top.pengdong.common.pojo.User;
import top.pengdong.dachuang.main.service.UserService;
import top.pengdong.dachuang.main.util.JwtTokenUtil;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @projectName: dachuang
 * @see: top.pengdong.dachuang.service.impl
 * @author: pc
 * @createTime: 2022/3/11 10:16
 * @version: 1.0
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

	@Resource
	private UserDetailsService userDetailsService;

	@Resource
	private PasswordEncoder passwordEncoder;

	@Resource
	private JwtTokenUtil jwtTokenUtil;

	@Resource
	private UserMapper userMapper;

	@Value("${jwt.tokenHead}")
	private String tokenHead;

	@Value("${jwt.baseUrl}")
	private String baseUrl;

	@Override
	public ResultResponse logout(String username) {
		return null;
	}

	@Override
	public ResultResponse login(String username, String password, String code) {
		// 验证码校验
//		String captcha = (String) request.getSession().getAttribute("captcha");
//		if (StringUtils.isEmpty(captcha) || !captcha.equalsIgnoreCase(code)) {
//			return ResultResponse.fail(ResultCode.CODE_PASS_ERROR);
//		}

		UserDetails userDetails = userDetailsService.loadUserByUsername(username);

		if (null == userDetails || !passwordEncoder.matches(password, userDetails.getPassword())) {
			return ResultResponse.fail(ResultCode.USER_PASS_ERROR);
		}
		if (!userDetails.isEnabled()) {
			return ResultResponse.fail(ResultCode.SIGN_ERROR);
		}
		log.info("用户登陆用户信息: {}" + userDetails);
		// 更新security登陆用户对象
		UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
				userDetails, null, userDetails.getAuthorities()
		);
		SecurityContextHolder.getContext().setAuthentication(authenticationToken);

		String token = jwtTokenUtil.generateToken(userDetails);
		JWT jwt = JWTUtil.parseToken(token);
		Map<String, Object> tokenMap = new HashMap<>();
		tokenMap.put("token", token);
		tokenMap.put("tokenHead", tokenHead);
		return ResultResponse.ok("登录成功", tokenMap);
	}

	@Override
	public User getUserByUsername(String username) {
		if (username == null) return null;
		UserExample example = new UserExample();
		UserExample.Criteria criteria = example.createCriteria();
		criteria.andUsernameEqualTo(username);
		List<User> list = userMapper.selectByExample(example);
		return list.size() > 0 ? list.get(0) : null;
	}

	@Override
	public ResultResponse getUserInfo(String headerValue) {
		String username = jwtTokenUtil.getUserNameFromToken(headerValue.substring(tokenHead.length() + 1));
		User user = getUserByUsername(username);
		user.setPassword(null);
		return ResultResponse.ok(user);
	}
}
